package me.huangxiang.concurrent;

import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static class AddThread implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 1000; i++){
                atomicInteger.incrementAndGet();
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(5);


        for (int i = 0; i < 7; i++){
            es.submit(new AddThread());
        }


//        Thread[] threads = new Thread[10];
//
//        Arrays.stream(threads).forEach(thread -> {
//            thread = new Thread(new AddThread());
//            thread.start();
//            try {
//                thread.join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        });


        try {
            // 在这里添加这个函数等待提交给线程池的任务工作完成。到此为止比较准确地理解了线程池的使用。
            es.awaitTermination(2, TimeUnit.SECONDS);
            System.out.println(atomicInteger.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            es.shutdown();
        }

    }
}
